package pl.enigmatic.parser.xml.pl.edu.enigma.math.perm;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import pl.enigmatic.math.perm.LatinsPermutation;
import pl.enigmatic.math.perm.Permutation;
import pl.enigmatic.util.Alphabet;
import pl.enigmatic.util.Arrays;
import pl.enigmatic.util.XML;
import pl.enigmatic.parser.xml.Parser;
import pl.enigmatic.parser.xml.ParsingInfo;


public class LatinsPermutationParser extends Parser<LatinsPermutation> {

	public LatinsPermutationParser() {
		super(LatinsPermutation.class, false);
	}

	private static void put(final Map<Integer, Integer> map, final Node node) {
		final int key = Alphabet.number(node.getNodeName().charAt(0));
		final int val = Alphabet.number(XML.getText(node).charAt(0));
		map.put(key, val);
	}

	@Override
	public LatinsPermutation parse(final ParsingInfo<LatinsPermutation> info) {
		final Element node = info.getElement();
		final NodeList children = node.getChildNodes();
		if (children.getLength() > 0) {
			final Node child = node.getFirstChild();
			if (child.getNodeType() == Node.TEXT_NODE) { return convert(XML.getText(child), info); }
		}
		final Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < children.getLength(); i++) {
			put(map, children.item(i));
		}
		final NamedNodeMap attr = node.getAttributes();
		for (int i = 0; i < attr.getLength(); i++) {
			put(map, attr.item(i));
		}
		return LatinsPermutation.fromArray(Permutation.makeCorrect(map, Arrays.identity(LatinsPermutation.LETTERS_NUM)));
	}

}
